import baseURL from './config.js'

let requestCount = 0 // 请求计数器

// 显示加载提示
const showLoading = () => {
	requestCount++
	if (requestCount === 1) {
		uni.showLoading({ title: 'Loading...', mask: true })
	}
}

// 隐藏加载提示
const hideLoading = () => {
	requestCount = Math.max(0, requestCount - 1)
	if (requestCount === 0) {
		uni.hideLoading()
	}
}

// 获取平台相关数据
const getPlatformInfo = () => {
	const systemInfo = uni.getSystemInfoSync()
	let version = '', platform = ''

	// #ifdef H5
	version = systemInfo.appVersion
	platform = 'h5'
	// #endif
	// #ifndef H5
	version = systemInfo.appWgtVersion
	platform = systemInfo.platform
	// #endif

	return { version, platform }
}

// 网络检查
const checkNetwork = () => {
	return new Promise((resolve, reject) => {
		uni.getNetworkType({
			success: ({ networkType }) => {
				if (networkType === 'none' || networkType === 'unknown') {
					uni.showToast({ title: 'Network unavailable', icon: 'none' })
					reject(new Error('Network error'))
				} else {
					resolve()
				}
			},
			fail: () => reject(new Error('Network check failed'))
		})
	})
}

const request = async (config) => {
	try {
		// 网络检查
		await checkNetwork()

		// 初始化配置
		const { version, platform } = getPlatformInfo()
		const isUpload = config.url === '/oss/upload'
		let token
		// #ifdef H5
		token = uni.getStorageSync('token') || '';
		// #endif
		// #ifndef H5
		token = plus.storage.getItem('token') || ''
		// #endif
		const fullConfig = {
			timeout: 15000, // 15秒超时
			...config,
			url: baseURL + config.url,
			data: config.data || {},
			header: {
				'token': token,
				'Content-Type': isUpload ? 'multipart/form-data' : 'application/json',
				'lang': 'en_US',
				'gc-agent': platform,
				'gc-version': version,
				...config.header
			}
		}

		showLoading()

		const response = await uni.request(fullConfig)
		const resData = response.data

		if (resData.code === 0) {
			return resData
		} else {
			// 特殊状态码处理
			switch (resData.code) {
				case 2001:
				case 2005:
					uni.showToast({
						title: resData.msg,
						icon: 'none'
					})
					let timer = setTimeout(() => {
						uni.setStorageSync('token', '')
						uni.reLaunch({
							url: "/pages/login/login"
						})
					}, 600)

					break
				case 2110:
					uni.$emit('refreshEvent')
					break
				default:
					uni.showToast({ title: resData.msg || 'Error', icon: 'none' })
			}
			return Promise.reject(resData)
		}
	} catch (error) {
		const errMsg = error.errMsg || ''
		if (errMsg.includes('timeout')) {
			uni.showToast({ title: 'Request timeout', icon: 'none' })
		} else if (!errMsg.includes('Network error')) {
			uni.showToast({ title: 'Request failed', icon: 'none' })
		}
		return Promise.reject(error)
	} finally {
		hideLoading()
	}
}

/**
 * 统一请求方法
 * @param {string} method 请求方法（GET、POST等）
 * @param {string} url 请求地址
 * @param {object} data 请求参数
 * @returns {Promise} 返回请求结果
 */
export function fetchData(method, url, data = {}) {
	return request({
		method,
		url,
		...(method.toLowerCase() === "GET" ? { params: data } : { data }), // GET 请求使用 params，其他请求使用 data
	});
}